package com.common.tools.widget;

import java.io.File;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;

import com.common.tools.http.CommonHttpClient;
import com.common.tools.util.CommonUtil;
import com.common.tools.util.FileUtil;
import com.common.tools.util.ImageUtil;

public class UrlImageView extends ImageView{
	
	private static final int MSG_DONWLOAD_COMPLETE = 1;
	private static final int MSG_DONWLOAD_ERROR = 2;
	
	private String url;
	private File cacheFile;
	private Thread downloadImageThread;
	private int defaultImageResource;
	
	public UrlImageView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public UrlImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public UrlImageView(Context context) {
		super(context);
	}

	
	public void setDefaultImageResource(int defaultImageResource) {
		this.defaultImageResource = defaultImageResource;
	}

	public void loadImageFromUrl(String url){
		this.url = url;
		
		String md5Url = CommonUtil.toMd5(url.getBytes());
		String cachePath = CommonUtil.getStorePath(getContext(), true);
		String filePath = cachePath + "/" + md5Url;
		
		Log.i("urlimage", " loadImageFromUrl >>>  url  >>>>  " + url);
		Log.i("urlimage", " loadImageFromUrl >>>  filePath  >>>>  " + filePath);
		
		File file = new File(filePath);
		if(file.exists()){
			cacheFile = file;
			
			handler.sendEmptyMessage(MSG_DONWLOAD_COMPLETE);
		}else{
			cacheFile = FileUtil.createFile(filePath);
			
			downloadImageThread = new Thread(downloadImageRunnable);
			downloadImageThread.start();
		}
		
		
		
	}
	
	public void interruptDownloadImage(){
		if(downloadImageThread!=null){
			downloadImageThread.interrupt();
			cacheFile.delete();
		}
	}
	
	private Runnable downloadImageRunnable = new Runnable() {
		
		@Override
		public void run() {
			
			CommonHttpClient client = new CommonHttpClient(url,getContext());
			
			try {
				client.get(cacheFile.getPath());
				handler.sendEmptyMessage(MSG_DONWLOAD_COMPLETE);
			} catch (Exception e) {
				handler.sendEmptyMessage(MSG_DONWLOAD_ERROR);
				e.printStackTrace();
			}
		}
	};
	
	private Handler handler = new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_DONWLOAD_COMPLETE:
				Bitmap bitmap = ImageUtil.readBitMap(getContext(), cacheFile.getPath());
				if(bitmap!=null){
					setImageBitmap(bitmap);
				}else{
					setImageResource(defaultImageResource);
				}
				
				break;
			case MSG_DONWLOAD_ERROR:
				cacheFile.delete();
				setImageResource(defaultImageResource);
				break;
			default:
				break;
			}
			
		};
	};
	
}
